import xbmc
import xbmcgui
import urllib, urllib2
import os, sys, re

__cwd__      = sys.modules[ "__main__" ].__cwd__
__settings__ = sys.modules[ "__main__" ].__settings__
__htm__      = sys.modules[ "__main__" ].__htm__
__test__     = sys.modules[ "__main__" ].__test__

class GUI(xbmcgui.WindowXML):
	def __init__(self, *args, **kwargs):
		xbmcgui.WindowXMLDialog.__init__(self, *args, **kwargs)
		self.genre_id = kwargs['id']
		self.genre_name = kwargs['name']
		print 'Genre : [%s] - [%s]' % (self.genre_id, self.genre_name)
		self.label = self.genre_name
		self.doModal()

	def onInit(self):
		self.testmode = __settings__.getSetting('testmode')
		self.page_number = '1'
		self.page = ''
		self.action_cancel_dialog = (9, 10)
		self.list = self.getControl(82)
		self.page_list = self.getControl(83)
		self.list.reset()
		self.page_list.reset()
		self.getControl(81).setLabel(self.label + ' :' )
		if __test__:
			__htm__.getPage(url=__cwd__ + '\\samples\\genre.htm', txdata=None)
		else:
			__htm__.getPage(url='http://www.vplay.ro/serials/?genreid=' + self.genre_id + '&page=1', txdata=None)
		self.page = __htm__.Page
		self.getControl(57).setImage(__htm__.UserAvatar)
		self.getControl(58).setLabel(__htm__.UserID)
		self.getControl(59).setLabel(__htm__.UserDays + ' zile VIP')
		self.RefreshItems()
		self.RefreshPages()

	def onClick(self, controlId):
		# print 'Control ID : [%s]' % str(controlId)
		if controlId == 9002:
			print 'Favorites'
			import resources.lib.Fav as Fav
			page_fav = Fav.GUI("vplay_fav.xml", __cwd__, "default")
			# self.close()
		elif controlId == 9003:
			import resources.lib.GenreList as GenreList
			page_genre_list = GenreList.GUI("vplay_genre_list.xml", __cwd__, "default")
			
		elif controlId == 9004:
			keyboard = xbmc.Keyboard('', 'Enter keyword:', False)
			kw = ''
			canceled = 'false'
			while (kw=='' and canceled=='false') :
				keyboard.doModal()
				if (keyboard.isConfirmed()):
					kw = keyboard.getText()
				if len(kw)==0:
					canceled='true'
			if canceled=='false':
				print 'Keyword : [%s]' % kw
				import resources.lib.Search as Search
				page_search = Search.GUI("vplay_search.xml", __cwd__, "default", keyword=kw)
				
		elif controlId == 9005:
			print 'Login'
			__settings__.openSettings()

		elif controlId == 82:
			item = self.list.getSelectedItem()
			# =================================================================================================
			# PLAY the item!
			# if (self.testmode != 'true'):
			import resources.lib.Serie as Serie
			page_serie = Serie.GUI("vplay_serie.xml", __cwd__, "default", id = item.getProperty('id'))
			# =================================================================================================
			# else:
				# print 'Item : [%s]' % item.getLabel()
				# print 'ID   : [%s]' % item.getProperty('id')
			# =================================================================================================
		elif controlId == 83:
			item = self.page_list.getSelectedItem()
			page_nr = item.getProperty('id')
			if not page_nr=='inactive':
				if not page_nr=='ppsel':
					self.page_number = page_nr
					print '================== Loading genre [%s] page [%s] :' % (self.genre_id, self.page_number)
					__htm__.getPage(url='http://www.vplay.ro/serials/?genreid=' + self.genre_id + '&ord=&page=' + self.page_number, txdata=None)
					self.page = __htm__.Page
					self.RefreshItems()
					self.RefreshPages()
	
	def RefreshItems(self):
		self.list.reset()
		items = re.compile('Seriale Online: (.+?)".+?img src="(.+?)"').findall(self.page)
		for title, img in items:
			id = img[ img.rfind('/') + 1 : img.rfind('.') ]
			print '[%s] - [%s] - [%s]' % (id, title, img)
			if self.testmode=='true':
				img = ''
			item = xbmcgui.ListItem( label=title, iconImage=img, thumbnailImage=img )
			item.setProperty('id', id)
			self.list.addItem(item)

	def RefreshPages(self):
		pages = re.compile('class="ppage(.+?)>(.+?)</a>').findall(self.page)
		self.page_list.reset()
		for id, lbl in pages:
			item = xbmcgui.ListItem()
			id = id.replace('"','').strip()
			if (id.find('rel')>=0):
				id = id.split('=')[1]
			lbl = lbl.replace('&raquo;','>').replace('&laquo;','<').replace(' Anterioara','')
			if(lbl.find('Urm')>=0):
				lbl = '>'
			print 'Page %s : "%s"' % (id, lbl)
			item.setLabel( lbl )
			item.setProperty('id', id)
			
			if id=='inactive':
				item.setInfo('video', {'trailer':'i'})
			elif id=='ppsel':
				item.setInfo('video', {'trailer':'s'})
			else:
				item.setInfo('video', {'trailer':'n'})
			
			self.page_list.addItem(item)
		if (self.page_list.size()>0):
			self.getControl(81).setLabel(self.label + ' - pag. ' + self.page_number + ' :' )

	def onAction(self, action):
		if action in self.action_cancel_dialog:
			self.close()

	def onFocus(self, controlId):
		pass
